import { Text, View } from '@tarojs/components';
import { Formik, FormikConfig, FormikProps, useField, FormikValues } from 'formik';
import theme from '@/theme';
import classNames from 'classnames';
import { FormConfigContext } from './utils';
import { pxTransform } from '@tarojs/taro';
import { useEffect, useRef, useState } from 'react';

export interface FormProps {
  direction?: 'horizontal' | 'vertical';
  /** 如果设置了这个，全部formitem用这个 */
  disabled?: boolean;
  /** 是否静态展示表单， 以formItem的staticed为主 */
  staticed?: boolean;
  /** 水平模式的label宽度 */
  labelWidth?: number | string;
  debug?: boolean;
}

function Form<Values extends FormikValues = FormikValues>({
  direction = 'horizontal',
  disabled,
  staticed,
  labelWidth = 120,
  children,
  debug = false,
  ...props
}: FormikConfig<Values> & FormProps) {
  return (
    <View className={classNames('pd-form')}>
      <FormConfigContext.Provider
        value={{
          direction,
          disabled,
          staticed,
          labelWidth: typeof labelWidth === 'number' ? pxTransform(labelWidth) : labelWidth,
          debug,
        }}>
        {debug && <DebugBox formRef={props.innerRef} />}
        <Formik {...props}>{children}</Formik>
      </FormConfigContext.Provider>
    </View>
  );
}

function DebugBox({ formRef }: any) {
  const [str, setStr] = useState('');
  const timerRef = useRef<any>(0);
  useEffect(() => {
    timerRef.current = setInterval(() => {
      if (formRef.current) {
        const str1 = JSON.stringify(formRef.current?.values, null, 2);
        if (str1 == str) {
          return;
        }
        setStr(str1);
      }
    }, 1500);
    return () => {
      clearInterval(timerRef.current);
    };
  }, [formRef, str]);

  const textStyle: React.CSSProperties = {
    fontSize: 12,
  };
  if (process.env.TARO_ENV === 'h5' || process.env.TARO_ENV === 'weapp') {
    textStyle.whiteSpace = 'pre-wrap';
  }
  return (
    <View>
      debug: <Text style={textStyle}>{str}</Text>
    </View>
  );
}
export default Form;
